<template>
    <div class="export-info">
        <h3>订阅信息设置</h3>

        <div class="search" v-loading="loading">
            <select-module label="选择地区：" :options="cities" :keyName="`valueid`" :contentName="`valuename`" v-model="cityIds"
                @click="areaAfterQuery"></select-module>

            <select-module label="选择分类：" :options="classifyList" :keyName="`valueid`" :contentName="`valuename`" v-model="classifyIds"
                @click="classAfterQuery"></select-module>

            <select-module label="所属行业：" :options="majorList" :keyName="`valueid`" :contentName="`valuename`" v-model="majorIds"
                @click="majorAfterQuery"></select-module>

            <!-- <select-module
                label="公告类型："
                :options="noticeList"
                :keyName="`valueid`"
                :contentName="`valuename`"
                v-model="noticeIds"
            ></select-module> -->

            <typeselect :label="'公告类型:'" :type-list="newnoticeList" :active-value="newnoticeIds" @setType="getnoticeSelect"
                @click="noticeAfterQuery"></typeselect>

            <div class="other">
                <div class="key-word">
                    <div class="title">关键词设置：</div>
                    <el-input v-model="keyWord" size="mini" placeholder="请输入3-5个关键词﹐每个关键词最多10个字﹐用空格隔开" clearable></el-input>
                </div>
                <div class="matching">
                    <div class="title">匹配设置：</div>
                    <el-radio-group v-model="radio">
                        <el-radio :label="1">包含任一关键词</el-radio>
                        <el-radio :label="2">包含所有关键词</el-radio>
                    </el-radio-group>
                </div>
            </div>
        </div>

        <div class="export-setting">
            <h3>导出设置</h3>

            <div class="time-setting">
                <div class="title">选择时间范围:
                    &nbsp;&nbsp;&nbsp;

                    <el-date-picker
                        v-model="startDate"
                        size="mini"
                        type="date"
                        placeholder="开始日期"
                        value-format="yyyy-MM-dd" 
                        :picker-options="startOptions"
                    ></el-date-picker>

                    <el-date-picker
                        v-model="endDate"
                        size="mini"
                        type="date"
                        placeholder="结束日期"
                        value-format="yyyy-MM-dd" 
                        :picker-options="endOptions"
                    ></el-date-picker>
                </div>
            </div>

            <div class="record-info">共计 <span>{{total}}</span> 条记录，支持导出格式为：xlsx</div>

            <div class="export-btn">
                <el-button 
                type="primary" 
                @click="exportClick" 
                size="small" 
                :disabled="loading"
                v-czc="['数据报表', '点击按钮' , '导出订阅信息',0 ,'dataExport-btn-exportInfo']"
                >
                    导出
                </el-button>
            </div>

        </div>

        <div class="export-footer">
            <h3>导出内容示例</h3>
            <img :src="img" alt="">
        </div>

    </div>
</template>

<script>
import dialogWaitList from '@js/dialog-wait-list.js';
import selectModule from '@/pages/application/info/components/select-module.vue';
import selectMultipletModule from '@/pages/application/info/components/select-multiple-module.vue';
import typeselect from './typeselect.vue';
import { mapGetters, mapActions } from 'vuex';
import tool from '../mixins/tool';

export default {
    head: {},
    mixins:[tool],
    components: {
        selectModule,
        selectMultipletModule,
        typeselect,
    },
    async asyncData(context) {},
    props:{
        typeName: {
            type: String,
            default: ""
        },
        num: {
            type: [String,Number],
            default: 0
        },
        unit:{
            type: String,
            default: "条"
        },
        code:{
            type: String,
            default: ""
        },
    },
    data() {
        return {
            loading: false,
            cityIds: [],

            classifyList: [
                { valueid: '1', valuename: '工程建设类' },
                { valueid: '2', valuename: '政府采购类' },
            ],
            classifyIds: [],

            majorList: [],
            majorIds: [],

            noticeList: [
                { valueid: '1', valuename: '招标公告' },
                { valueid: '2', valuename: '变更公告' },
                { valueid: '3', valuename: '中标候选人公示 ' },
                { valueid: '4', valuename: '中标公告' },
            ],
            noticeIds: [],

            newnoticeList: [
                { valueid: '', valuename: '全部' },
                { valueid: '1', valuename: '招标公告' },
                { valueid: '2', valuename: '变更公告' },
                { valueid: '3', valuename: '中标候选人公示 ' },
                { valueid: '4', valuename: '中标公告' },
                { valueid: '5', valuename: '政府采购意向' },
                { valueid: '6', valuename: '政府采购意向变更' },
                { valueid: '7', valuename: '招标计划公告' },
            ],
            newnoticeIds: '',

            keyWord: '',
            radio: 1,

            time: '',
            startDate: '',
            endDate: '',

            img: '/images/tool/dyxx.png',
            total: 0,
        };
    },
    computed: {
        startOptions() {
            return {
                firstDayOfWeek: 1,
                disabledDate: (time) => {
                    let minDate = '2016-09-24 00:00',
                        fixedMinDateTime = new Date(minDate).getTime(),
                        fixedMaxDateTime = new Date().getTime();

                    var minDateTime = fixedMinDateTime,
                        maxDateTime = fixedMaxDateTime;

                    if (this.endDate) {
                        let toMinDateTime = new Date(this.endDate).getTime() - (30 * 24 * 60 * 60 * 1000);

                        minDateTime = Math.max(toMinDateTime, fixedMinDateTime);

                        maxDateTime = new Date(this.endDate).getTime();
                    }

                    return (
                        time.getTime() > maxDateTime 
                        || time.getTime() < minDateTime
                    );
                }
            };
        },
        endOptions() {
            return {
                firstDayOfWeek: 1,
                disabledDate: (time) => {
                    let minDate = '2016-09-24 00:00',
                        fixedMinDateTime = new Date(minDate).getTime(),
                        fixedMaxDateTime = new Date().getTime();

                    var minDateTime = fixedMinDateTime,
                        maxDateTime = fixedMaxDateTime;

                    if (this.startDate) {
                        minDateTime = new Date(this.startDate).getTime();

                        let toMaxDateTime = new Date(this.startDate).getTime() + (30 * 24 * 60 * 60 * 1000);

                        maxDateTime = Math.min(toMaxDateTime, fixedMaxDateTime);
                    }

                    return (
                        time.getTime() > maxDateTime 
                        || time.getTime() < minDateTime
                    );
                }
            };
        },
        cities() {
            return this.$store.getters['city/getCitiesByProvinceCode']('130000');
        },
        pgData() {
            return {
                regionCode: this.cityIds.toString(),
                projectClassifyCode: this.classifyIds.toString(),
                tenderProjectIndustriesType: this.majorIds.toString(),
                noticeType: this.newnoticeIds,
                keyWord: this.keyWord,
                matchRule: this.radio,
                startDate: this.startDate,
                endDate: this.endDate,
                isExport: false,
            };
        },
    },

    watch: {
        startDate: {
            handler(n,o){
                if (!!this.startDate && !!this.endDate) {
                    this.getDataList();
                } else {
                    this.total = 0;
                }
            },
            deep: true,
        },
        endDate: {
            handler(n,o){
                if (!!this.startDate && !!this.endDate) {
                    this.getDataList();
                } else {
                    this.total = 0;
                }
            },
            deep: true,
        },
    },

    methods: {
        ...mapActions({
            queryCity: 'city/queryCities',
            queryStatisticData: 'userinfo/queryStatisticData',
        }),
        autoDownUrl() {
            let targetUrl = this.$route.fullPath;
            if(targetUrl.indexOf("regionCode") == -1 ){
                return;
            }

            let targetData = {
                regionCode: this.getQuery('regionCode'),
                projectClassifyCode: this.getQuery('projectClassifyCode'),
                tenderProjectIndustriesType: unescape(this.getQuery('tenderProjectIndustriesType'))  ,
                noticeType: this.getQuery('noticeType'),
                keyWord: this.getQuery('keyWord'),
                matchRule: this.getQuery('matchRule'),
                startDate: this.getQuery('startDate'),
                endDate: this.getQuery('endDate') ,
                isExport: false,
            };
            
            this.time = targetData.startDate + '-' +targetData.endDate;

            //调用下载方法
            this.getDataList(targetData , this.exportClick);
        },

        back() {},
        getnoticeSelect: function (val) {
            this.newnoticeIds = val.valueid;
        },

        getClassifyList: function () {
            this.$get(`${this.$store.state.api.tbUrl}/searchrelated/getclassify.json`, {}, function (data) {
                this.classifyList = data;
            });
        },

        getMajorList() {
            this.$get(`${this.$store.state.api.tbUrl}/searchrelated/getindustries.json`, {}, (data, res) => {
                this.majorList = data;
            });
        },

        getDataList: function (dataSelf ,cb) {
            this.loading = true;
            let data ;
            if(dataSelf){
                data = dataSelf;
            }else{
                data = this.pgData;
            }
            this.$get(`${this.$store.state.api.tbUrl}/dateExport/subInfo`, data, (data, res) => {
                this.total = data.total;
                this.loading = false;
                cb && cb(dataSelf);
            });
        },

        exportData(dataSelf){
            if (this.total == 0) {
                return ShowMsg('共计 0 条记录,暂不支持导出', 'warning');
            }
            if (!this.startDate && !this.endDate) {
                return ShowMsg('选择时间后进行导出', 'warning');
            } 

            ShowConfirm('是否导出当前数据信息', 'warning', () => {
                let newObj = clone(this.pgData);
                if(dataSelf){
                    newObj = dataSelf;
                }
                newObj.isExport = true;

                var search = toSearch(newObj);
                downloader(`${this.$store.state.api.tbUrl}/dateExport/subInfo${search}`);
                this.startDate = '';
                this.endDate='';
                this.useNums('DYXX');
                return ShowMsgBox('导出成功，即将自动下载附件，请勿关闭页面', 'success');
            });
        },

        areaAfterQuery(item, index) {
            this.setCzc(['数据报表', '筛选' , '地区', index ,'dataExport-select-city'])
        },
        classAfterQuery(item, index) {
            this.setCzc(['数据报表', '筛选' , '分类', index ,'dataExport-select-class'])
        },
        majorAfterQuery(item, index) {
            this.setCzc(['数据报表', '筛选' , '行业', index ,'dataExport-select-major'])
        },
        noticeAfterQuery(item, index) {
            this.setCzc(['数据报表', '筛选' , '公告类型', index ,'dataExport-select-noticeType'])
        },
    },
    created() {},
    mounted() {
        this.getMajorList();
        this.getClassifyList();
        this.autoDownUrl();

        this.queryCity();

        // 获取服务权限次数
        this.queryStatisticData(arr => {
            var service = arr.filter(item => item.code === 'DYXX'),
                remain = service[0].surplus;

            if (remain <= 0 || !remain) {
                // 没次数
                return;
            }

            // 在列队中注册-分享引导登录
            dialogWaitList.push(() => {
                this.$alert(`您有${remain}次导出订阅信息的次数，点击导出只消耗1次`, '提示', {
                    confirmButtonText: '确定',
                    type: 'success',
                }).then(() => {
                    dialogWaitList.next();
                });
            }, 4);
        });
    },
};
</script>

<style lang="scss" scoped>
@import '@css/var.scss';
.export-info {
    & > h3 {
        margin-top: 10px;
    }
    .re-span {
        font-size: 14px;
        color: #999;
    }
    .search {
        margin-top: 20px;

        .other {
            display: flex;
            justify-content: space-between;
            align-items: baseline;
            margin-top: 15px;
            width: 860px;

            div {
                display: flex;
                justify-content: space-between;
                align-items: baseline;

                .title {
                    font-weight: 600;
                }
            }

            .key-word {
                width: 480px;
                .title {
                    width: 120px;
                }
            }
        }
    }

    .export-setting {
        margin-top: 25px;

        .time-setting {
            margin-top: 20px;
            font-weight: 600;
        }
        .record-info {
            margin-top: 1em;
            font-size: 12px;
        }
        .export-btn {
            display: flex;
            justify-content: center;
            margin-top: 80px;
            margin-bottom: 40px;

            .el-button {
                width: 105px;
            }
        }
    }

    .export-footer {
        margin-top: 20px;

        img {
            width: 99%;
            margin-top: 15px;
        }
    }
}
</style>
